﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.TextMining.FullTextSearch
{
	/// <summary>
	/// 
	/// </summary>
	public partial class SqlFullTextSearchEditor : Form, IComponentEditor
	{
		/// <summary>
		/// 
		/// </summary>
		public SqlFullTextSearchEditor()
		{
			InitializeComponent();
		}

		private void SqlFullTextSearchEditor_Load(object sender, EventArgs e)
		{

		}

		#region Implementation of IComponentEditor

		private object _ActivityNode;
		private SqlFullTextSearchComponent _SearchComponent;

		public event UpdateComponentSettings UpdateComponentSettingEvent;

		/// <summary></summary>
		public object OwnerActivityNode
		{
			get { return _ActivityNode; }
			set { _ActivityNode = value; }
		}

		/// <summary></summary>
		public Type WorkflowComponentType
		{
			get { return typeof (SqlFullTextSearchComponent); }
		}

		/// <summary></summary>
		public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents, object activityNode, WorkflowComponentBase wfComponent)
		{
			this._ActivityNode = activityNode;
			this._SearchComponent = (SqlFullTextSearchComponent) wfComponent;

			SqlFullTextSearchInstruction instruction = (SqlFullTextSearchInstruction) this._SearchComponent.Instruction;
			this.txt_ConnStr.Text = instruction.ConnStr;
			this.PopulateTables(instruction.ConnStr);
			this.SelectComboxField(this.cbo_Tables,instruction.TableName);
			this.SelectComboxField(this.cbo_KeyField,instruction.KeyField);
            this.SelectComboxField(this.cbo_TitleField, instruction.TitleField);
			this.txt_Query.Text = instruction.Query;
			this.txt_SearchResultFile.Text = instruction.SearchResultFilePath;
			this.dv_Fields.Rows.Clear();
			if(instruction.TextFieldWeights !=null && instruction.TextFieldWeights.Count>0)
			{
				foreach(string fieldName in instruction.TextFieldWeights.Keys)
				{
					DataGridViewRow dr = new DataGridViewRow();
					DataGridViewTextBoxCell cellFieldName=new DataGridViewTextBoxCell();
					cellFieldName.Value = fieldName;
					dr.Cells.Add(cellFieldName);
					DataGridViewTextBoxCell cellWeight=new DataGridViewTextBoxCell();
					cellWeight.Value = instruction.TextFieldWeights[fieldName];
					dr.Cells.Add(cellWeight);
                    DataGridViewCheckBoxCell cellInclude=new DataGridViewCheckBoxCell();
                    if(instruction.IncludedTextFields !=null && 
                        instruction.IncludedTextFields.Contains(fieldName))
                        cellInclude.Value = true;
                    else
                        cellInclude.Value = false;
				    dr.Cells.Add(cellInclude);
					this.dv_Fields.Rows.Add(dr);
				}
			}
		}

		private void PopulateTables(string connStr)
		{
			this.cbo_Tables.Items.Clear();
			string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, string.Empty, connStr);
			if(tblNames !=null && tblNames.Length>0)
			{
				foreach(string tblName in tblNames)
				{
					this.cbo_Tables.Items.Add(tblName);
				}
			}
		}

		private void SelectComboxField(ComboBox comboBox, string field)
		{
			if(!string.IsNullOrEmpty(field) && comboBox.Items.Count>0)
			{
				for(int i=0;i<comboBox.Items.Count;i++)
				{
					if(comboBox.Items[i].ToString()==field)
					{
						comboBox.SelectedIndex = i;
						break;
					}
				}
			}
		}

		/// <summary></summary>
		public void SaveSettings()
		{
			SqlFullTextSearchInstruction instruction = (SqlFullTextSearchInstruction)this._SearchComponent.Instruction;
			instruction.ConnStr = this.txt_ConnStr.Text;
			instruction.TableName = this.cbo_Tables.Text;
			instruction.KeyField = this.cbo_KeyField.Text;
		    instruction.TitleField = this.cbo_TitleField.Text;
			instruction.Query = this.txt_Query.Text;
			instruction.SearchResultFilePath = this.txt_SearchResultFile.Text;
			instruction.TextFieldWeights=new Dictionary<string, double>();
            instruction.IncludedTextFields=new List<string>();
			foreach(DataGridViewRow dr in this.dv_Fields.Rows)
			{
				if(!dr.IsNewRow && dr.Cells[0].Value !=null)
				{
					string fieldName = (string) dr.Cells[0].Value;
					double weight = double.Parse(dr.Cells[1].Value.ToString());
				    bool include = bool.Parse(dr.Cells[2].Value.ToString());
                    if(include)
                        instruction.IncludedTextFields.Add(fieldName);
					instruction.TextFieldWeights.Add(fieldName,weight);
				}
			}
			this._SearchComponent.Instruction = instruction;
		}

		/// <summary></summary>
		public TestResult Test()
		{
			throw new System.NotImplementedException();
		}

		#endregion

		private void cbo_Tables_SelectedIndexChanged(object sender, EventArgs e)
		{
			if(!string.IsNullOrEmpty(this.txt_ConnStr.Text) && this.cbo_Tables.SelectedIndex>=0)
			{
				string tblName = this.cbo_Tables.SelectedItem.ToString();
				this.PopulateTableColumns(this.txt_ConnStr.Text,tblName);
			}
		}

		private void PopulateTableColumns(string connStr, string tblName)
		{
			this.cbo_KeyField.Items.Clear();
			this.cbo_TextField.Items.Clear();
            this.cbo_TitleField.Items.Clear();
			TableColumn[] cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, connStr, string.Empty, tblName);
			if(cols !=null && cols.Length>0)
			{
				foreach(TableColumn col in cols)
				{
					this.cbo_KeyField.Items.Add(col.ColumnName);
				    this.cbo_TitleField.Items.Add(col.ColumnName);
					this.cbo_TextField.Items.Add(col.ColumnName);
				}
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			this.PopulateTables(this.txt_ConnStr.Text);
		}

		private void btn_AddField_Click(object sender, EventArgs e)
		{
			if(this.cbo_TextField.SelectedIndex>0)
			{
				string fieldName = this.cbo_TextField.SelectedItem.ToString();
				double weight = (double) this.num_Weight.Value;
				DataGridViewRow dr = new DataGridViewRow();
				DataGridViewTextBoxCell cellFieldName = new DataGridViewTextBoxCell();
				cellFieldName.Value = fieldName;
				dr.Cells.Add(cellFieldName);
				DataGridViewTextBoxCell cellWeight = new DataGridViewTextBoxCell();
				cellWeight.Value = weight;
				dr.Cells.Add(cellWeight);
				this.dv_Fields.Rows.Add(dr);
			}
		}

		private void btn_SaveAs_Click(object sender, EventArgs e)
		{
			SaveFileDialog dlg=new SaveFileDialog();
			dlg.Filter = "Search result files(*.find)|*.find|All files(*.*)|*.*";
			if(dlg.ShowDialog()==DialogResult.OK)
				this.txt_SearchResultFile.Text = dlg.FileName;
		}

		private void btn_Cancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btn_OK_Click(object sender, EventArgs e)
		{
			this.SaveSettings();
			if (this.UpdateComponentSettingEvent != null)
				this.UpdateComponentSettingEvent(this._ActivityNode, this._SearchComponent);

			this.Close();
		}
	}
}
